//
//  AppDelegate.m
//  GeeCityManager
//
//  Created by 聚城科技 on 16/2/29.
//  Copyright © 2016年 聚城科技. All rights reserved.
//

#import "AppDelegate.h"
#import "GCMLoginViewController.h"
#import "GCMMainViewController.h"
#import "GCMReciveDetailViewController.h"
#import "GCMMain1ViewController.h"
#import "MCAdvertView.h"
#import "MCAdvertManager.h"
#import "GCMOUTLINEEquPlanViewController.h"
//极光推送
#import "XRQJpush.h"
//通知提示  主要是为了程序在前端的时候的提示
#import "JKNotifier.h"

@interface AppDelegate ()


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    /*
     加推送
     */
    [XRQJpush setupWithOptions:launchOptions];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
        //取出缓存
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSArray *userInfo = [user arrayForKey:@"arr"];
        
        if (userInfo != nil) {
            if ([GCMCZHRequst isExistenceNetwork]) {
                [self autoLoginWithUserName:userInfo[0] WithPassWord:userInfo[1]];
                [XRQJpush setBieming:userInfo[0]];
            }else{
                //       一会把跳转写到这
                NSUserDefaults *s = [NSUserDefaults standardUserDefaults];
                NSString *styleStr = [s valueForKey:@"style"];
                NSLog(@"%@",styleStr);
                if ([styleStr isEqualToString:@"现代风格"]) {
                    GCMMain1ViewController * mainVC1 =[[GCMMain1ViewController alloc]init];
                    UINavigationController *navc1 = [[UINavigationController alloc]initWithRootViewController:mainVC1];
                    self.window.rootViewController =navc1;
                    [self.window makeKeyAndVisible];
                    [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"isLook"];
                    [self initRootViewController];
                    
                }else{
                    GCMMainViewController * mainVC =[[GCMMainViewController alloc]init];
                    UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:mainVC];
                    self.window.rootViewController =navc;
                    [self.window makeKeyAndVisible];
                    [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"isLook"];
                    [self initRootViewController];
                }
            }
            
//            NSLog(@"userid------%@",userInfo);
            
        }else{
        
            self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            self.window.backgroundColor = [UIColor whiteColor];
            GCMLoginViewController * loginvc =[[GCMLoginViewController alloc]init];
            UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:loginvc];
            self.window.rootViewController =navc;
            [self.window makeKeyAndVisible];
//            设置启动页
            [self initRootViewController];
            [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"isLook"];
        }

    
    
    return YES;
    
}
/// 设置跟控制器
-(void)initRootViewController{
    // 启动图片
    [[MCAdvertManager sharedInstance] setAdvertViewController];
}

-(void)autoLoginWithUserName:(NSString *)username WithPassWord:(NSString *)password{

    [GCMLoginHttpRequst postUserInfoWithUserName:username AndPassWord:password Success:^(id userInfo, NSError *err) {
//        NSLog(@"++++%@",userInfo);
        if ([userInfo[@"success"] integerValue] == 1)
        {
            
            //            存数据
            NSMutableDictionary *infoDic  = [[NSMutableDictionary alloc]init];
            infoDic  = [userInfo valueForKey:@"data"];
            //            把数据缓存起来供使用
            [[NSUserDefaults standardUserDefaults]setObject:infoDic forKey:@"userInfo"];
            NSLog(@"=========%@",infoDic);
            [GCMUserInfo instance].areaId = [infoDic valueForKey:@"areaId"];
            [GCMUserInfo instance].auth = [infoDic valueForKey:@"auth"];
            [GCMUserInfo instance].departId = [infoDic valueForKey:@"departId"];
            [GCMUserInfo instance].uid = [infoDic valueForKey:@"id"];
            [GCMUserInfo instance].position = [infoDic valueForKey:@"position"];
            [GCMUserInfo instance].realName = [infoDic valueForKey:@"realName"];
            [GCMUserInfo instance].pic = [infoDic valueForKey:@"pic"];
            [GCMUserInfo instance].copyright = [infoDic valueForKey:@"copyright"];
            [GCMUserInfo instance].oaServer = [infoDic valueForKey:@"oaServer"];
            [GCMUserInfo instance].glc = [infoDic valueForKey:@"glc"];
            [GCMUserInfo instance].company = [infoDic valueForKey:@"company"];
            
            self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            self.window.backgroundColor = [UIColor whiteColor];
            
            
            //            登陆成功就进行统计
            [GCMMainHttpRequst ClickTimes:@"登陆" Success:^(id times, NSError *err) {
                NSLog(@"测试统计登陆次数成功");
                NSLog(@"%@",times);
            }];
            
            //       一会把跳转写到这
            NSUserDefaults *s = [NSUserDefaults standardUserDefaults];
            NSString *styleStr = [s valueForKey:@"style"];
            NSLog(@"%@",styleStr);
            if ([styleStr isEqualToString:@"现代风格"]) {
                GCMMain1ViewController * mainVC1 =[[GCMMain1ViewController alloc]init];
                UINavigationController *navc1 = [[UINavigationController alloc]initWithRootViewController:mainVC1];
                self.window.rootViewController =navc1;
                [self.window makeKeyAndVisible];
                [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"isLook"];
                [self initRootViewController];

            }else{
                GCMMainViewController * mainVC =[[GCMMainViewController alloc]init];
                UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:mainVC];
                self.window.rootViewController =navc;
                [self.window makeKeyAndVisible];
                [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"isLook"];
                [self initRootViewController];
            }
            
        }
        
    }];
    
}
/*****************
 
 推送的代理方法
 
 *****************/

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [XRQJpush registerDeviceToken:deviceToken];
    return;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    //    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [XRQJpush handleRemoteNotification:userInfo completion:nil];
    return;
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
// ios7.0以后才有此功能
- (void)application:(UIApplication *)application didReceiveRemoteNotification
                   :(NSDictionary *)userInfo fetchCompletionHandler
                   :(void (^)(UIBackgroundFetchResult))completionHandler {
    [XRQJpush handleRemoteNotification:userInfo completion:completionHandler];
    NSLog(@"-------%@",userInfo);
    // 应用正处理前台状态下，不会收到推送消息，因此在此处需要额外处理一下
    if (application.applicationState == UIApplicationStateActive) {
        
        [JKNotifier showNotifer:[NSString stringWithFormat:[[userInfo valueForKey:@"aps"] valueForKey:@"alert"]]];
        
        //        CLog(@"-------%@",userInfo);
        
        [JKNotifier handleClickAction:^(NSString *name,NSString *detail, JKNotifier *notifier) {
            [notifier dismiss];
            NSLog(@"点击可在这里边处理一些事情");
        }];
    }else{
        
        NSUserDefaults *s = [NSUserDefaults standardUserDefaults];
        NSString * style = [s valueForKey:@"style"];
        [s synchronize];

        if ([style isEqualToString:@"现代风格"]) {
            
            GCMMain1ViewController *main1 = [[GCMMain1ViewController alloc]init];
            UINavigationController *navc1 = [[UINavigationController alloc]initWithRootViewController:main1];
            [main1 pushToNotifyController1WithUserInfo:userInfo];
            self.window.rootViewController = navc1;
            
        }else{
            
            GCMMainViewController *main = [[GCMMainViewController alloc]init];
            UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:main];
            [main pushToNotifyControllerWithUserInfo:userInfo];
            self.window.rootViewController = navc;
        }
            
    }
    
    return;
}


#endif

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [XRQJpush showLocalNotificationAtFront:notification];
    if (application.applicationState == UIApplicationStateActive) {
        [JKNotifier showNotifer:notification.alertBody];
        
    }
    return;
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSLog(@"Error in registration. Error: %@", err);
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "GC-CZH.GeeCityManager" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"GeeCityManager" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"GeeCityManager.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
